package com.tianhui.consignortwofei.api;

import android.content.Intent;
import android.text.TextUtils;

import com.fgs.common.manager.ActivityManager;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.ui.activity.LoginActivityNew;
import com.tianhui.consignortwofei.utils.ApplicationUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author fgs
 * @date 2020/3/27
 **/
public class TokenHeaderInterceptor implements Interceptor {
    private boolean isTokenExpiredShow = false;

    @Override
    public Response intercept(Chain chain) throws IOException {
        String token = SharedPreferenceManager.getInstance().getToken();
        if (isNeedAddHeader(chain.request().url().toString())) {

            Request.Builder request = chain.request().newBuilder();
            //添加Token请求头 这里的token应当是从本地数据库中读取的 **********
            request.addHeader("Authorization", token);
            Response proceed = chain.proceed(request.build());
            if (isTokenExpired(proceed)) {
                LogUtil.print("=============>token过期0");
                if (!isTokenExpiredShow) {
                    isTokenExpiredShow = true;
                    SharedPreferenceManager.getInstance().setToken("");
                    ToastUtil.showShortToast("登录状态已失效，请重新登录");
                    LogUtil.print("=============>token过期1");
                    ActivityManager.getInstance().finishAllActivity();
                    Intent intent = new Intent(ApplicationUtil.getContext(), LoginActivityNew.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    ApplicationUtil.getContext().startActivity(intent);
                }
            }
            return proceed;
        } else {
            Request originalRequest = chain.request();
            return chain.proceed(originalRequest);
        }


    }

    /**
     * 根据Response，判断Token是否失效
     * 401表示token过期
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        String token = response.headers().get("token");
        if (!TextUtils.isEmpty(token)) {
            SharedPreferenceManager.getInstance().setToken(token);
            return false;
        }
        return response.code() == 401 || response.code() == 403;
    }

    private boolean isNeedAddHeader(String url) {
        if (TextUtils.isEmpty(url)) return false;

        return !url.contains("account/login") && !url.contains("customer/register") && !url.contains("account/getSMSCode") && !url.contains("account/resetPwd");
    }
}